package paritclecontainer2d;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.util.ArrayList;
import java.util.HashSet;

import javax.swing.JPanel;

public class ParticleCanvas extends JPanel implements Runnable{

	
	private Thread animatorThread;
	private boolean animating;
	
	private HashSet<Emiter> activeParticles;
	private boolean freezeParticle;
	
	public ParticleCanvas() {
		this.activeParticles = new HashSet<>();
		this.freezeParticle = false;
	}

	@Override
	public void paintComponent(Graphics arg) {
		Graphics g = arg;
		int cHeight = this.getSize().height;
		int cWidth = this.getSize().width;
		
		g.setColor(Color.BLACK);
		
		g.fillRect(0, 0, cWidth, cHeight);

		int particleCounter = 0;
		
		for(Emiter emiter : activeParticles){
			
			for(Particle particle : emiter.getParticles()){
				particle.paintComponent(arg);
				particleCounter++;
			}
		}
		
		g.setColor(Color.WHITE);
		g.drawString("Particles: "+particleCounter, 10, 20);
		
		if(freezeParticle){
			g.drawString("Frozen", 10, 35);
		}
	}

	
	public void addEmiter(Emiter emiter){
		activeParticles.add(emiter);
	}
	

	public void startAnimator(){
		if(animatorThread == null && !animating){
			animatorThread = new Thread(this);
			animating = true;
			animatorThread.start();
			
		}
	}

	@Override
	public void run() {
		while(animating){
			
			if(!freezeParticle){
				for(Emiter emiter : activeParticles){
					emiter.refreshParticles();
				}
			}
			
			repaint();
			try {
				Thread.sleep(5);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	public void freeze(boolean freeze){
		this.freezeParticle = freeze;
	}
	
	public boolean isFrozen(){
		return this.freezeParticle;
	}
}
